﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using Tesseract;

public class GetCodeHelper
{
    private Bitmap _changeImage;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="bitmap">需要ocr的图片</param>
    /// <param name="ocrFont">（训练）字库 默认为中文字库</param>
    /// <returns></returns>
    public string GetImageTextByOcr(Bitmap bitmap, string ocrFont= "chi_sim",Model.KBian kb=null,Model.ColorReplace colorReplace=null)
    {
        try
        {
            bitmap.Save(@"./1_ocr.jpg");
            if (string.IsNullOrEmpty(ocrFont))
                ocrFont = "chi_sim";
            ImageColorReplace(bitmap, colorReplace);
            
            ImageKBian(bitmap, kb);
            GrayBitmap2(bitmap);

            #region ocr
            var resultText = "";
            using (var engine = new TesseractEngine(@"./tessdata", ocrFont, EngineMode.Default))
            {
                using (var page = engine.Process(bitmap))
                {
                    resultText = page.GetText();
                }
            }

            return resultText.Replace(" ", "");

            #endregion
        }
        catch (Exception ex)
        {
            //记录错误日志
            //FileHelper.AppendErrorLogText(null, "方法：public string GetImageTextByOcr(Bitmap bitmap, string ocrFont)：" + ex.Message + "\r\n");
            //MessageBox.Show("ocr异常");
            return "";
        }

    }


    #region 图片处理
    //扩边
    public void ImageKBian(Bitmap bmpScreenShot, Model.KBian kbModel)
    {
        #region 扩大边界
        if (kbModel != null)
        {
            var t_color = bmpScreenShot.GetPixel(1, 1);
            var f_color = bmpScreenShot.GetPixel(1, bmpScreenShot.Height - 1);
            var l_color = bmpScreenShot.GetPixel(1, 1);
            var r_color = bmpScreenShot.GetPixel(1, bmpScreenShot.Height - 1);

            var newWidth = bmpScreenShot.Width + kbModel.Left + kbModel.Right;
            var newHeight = bmpScreenShot.Height + kbModel.Top + kbModel.Bottom;
            using (Bitmap newBmpScreenShot = new Bitmap(newWidth, newHeight))//根据上下左右的量扩大
            {
                //创建要显示的图片对象,根据参数的个数设置宽度
                //Bitmap backgroudImg = new Bitmap(100, 100);
                Graphics g = Graphics.FromImage(newBmpScreenShot);

                //清除画布,背景设置为白色
                g.Clear(t_color);

                g.DrawImage(bmpScreenShot, kbModel.Left, kbModel.Top, bmpScreenShot.Width, bmpScreenShot.Height);
                //左边
                for (int i = 0; i < kbModel.Left; i++)
                {
                    for (int j = 0; j < bmpScreenShot.Height; j++)
                    {
                        Color pixelColor = bmpScreenShot.GetPixel(1, j);
                        SolidBrush pixelBrush = new SolidBrush(pixelColor);
                        g.FillRectangle(pixelBrush, i, kbModel.Top + j, 1, 1);
                    }
                }

                //右边
                for (int i = 0; i < kbModel.Right; i++)
                {
                    for (int j = 0; j < bmpScreenShot.Height; j++)
                    {
                        Color pixelColor = bmpScreenShot.GetPixel(bmpScreenShot.Width - 1, j);
                        SolidBrush pixelBrush = new SolidBrush(pixelColor);
                        g.FillRectangle(pixelBrush, bmpScreenShot.Width + kbModel.Left + i, kbModel.Top + j, 1, 1);
                    }
                }

                //下边
                f_color = bmpScreenShot.GetPixel(1, bmpScreenShot.Height - 1);
                for (int i = 0; i < newBmpScreenShot.Width; i++)
                {
                    for (int j = 0; j < kbModel.Bottom; j++)
                    {
                        newBmpScreenShot.SetPixel(i, kbModel.Top + bmpScreenShot.Height + j, f_color);
                    }
                }
                newBmpScreenShot.Save(@"./img/1_ImageKBian.jpg");
                bmpScreenShot = newBmpScreenShot.Clone() as Bitmap;
            }
        }
        #endregion
         
    }

    public void ImageColorReplace(Bitmap bmpScreenShot, Model.ColorReplace crModel)
    {
        #region 颜色替换
        if (crModel != null)
        {
            var fromColor = ColorTranslator.FromHtml(crModel.FromColor);
            var toColor = ColorTranslator.FromHtml(crModel.ToColor);
            for (int i = 0; i < bmpScreenShot.Width; i++)
            {
                for (int j = 0; j < bmpScreenShot.Height; j++)
                {
                    Color pixelColor = bmpScreenShot.GetPixel(i, j);

                    if (pixelColor == fromColor)
                    {
                        bmpScreenShot.SetPixel(i, j, toColor);
                    }

                }
            }
            bmpScreenShot.Save(@"./img/1_ImageColorReplace.jpg");
        }
         
        #endregion
    }

    private bool ImageEquals(byte[] bmpOne, byte[] bmpTwo)
    {
        for (int i = 0; i < bmpOne.Length; i++)
        {
            if (bmpOne[i] != bmpTwo[i])
            {
                return false;
            }

        }
        return true;
    }

    public byte[] GetRgbArray(Bitmap bmp)
    {
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
        IntPtr ptr = bmpData.Scan0;
        int bytes = bmpData.Stride * bmp.Height;
        byte[] rgbValues = new byte[bytes];
        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
        bmp.UnlockBits(bmpData);

        return rgbValues;
    }

    private static ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }

    /// <summary>
    /// 灰度
    /// </summary>
    /// <param name="p"></param>
    /// <returns>返回二值化阀值</returns>
    public int GrayBitmap(Bitmap p)
    {
        DateTime d1 = DateTime.Now;
        Dictionary<int, int> pixelNums = new Dictionary<int, int>(); //用于计算峰值

        int w = p.Width;
        int h = p.Height;
        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                Color c = p.GetPixel(x, y);
                int rgb = Convert.ToInt32((double)(((0.3 * c.R) + (0.59 * c.G)) + (0.11 * c.B)));//转化成灰度
                p.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb));
                if (rgb < 35) continue;
                if (pixelNums.ContainsKey(rgb))
                {
                    pixelNums[rgb]++;
                }
                else
                {
                    pixelNums.Add(rgb, 1);
                }
            }
        }
        DateTime d2 = DateTime.Now;
        TimeSpan ts = d2 - d1;
        //MessageBox.Show(ts.ToString());

        int maxValue = 1;
        int maxColor = 1;
        foreach (KeyValuePair<int, int> num in pixelNums)
        {
            if (num.Value < 100) continue; //数量小于10的忽略
            if (num.Value > maxValue)
            {
                maxValue = num.Value;
                maxColor = num.Key;
            }
        }

        //int value = (int)(177 * 0.80);
        //for (int y = 0; y < h; y++)
        //{
        //    for (int x = 0; x < w; x++)
        //    {
        //        Color c = p.GetPixel(x, y);
        //        if (c.R <= value)
        //        {
        //            p.SetPixel(x, y, Color.FromArgb(0, 0, 0));
        //        }
        //        else
        //        {
        //            p.SetPixel(x, y, Color.FromArgb(255, 255, 255));
        //        }
        //    }
        //}
        // p.Save(Program.ocrChangeImagePath + "GrayBitmap_" + Strings.filenameshijian() + ".png", System.Drawing.Imaging.ImageFormat.Png);

        return (int)(177 * 0.80);

    }

    //改善对比度（灰度图像处理）
    public void GrayBitmap2(Bitmap p)
    {
        Color c = new Color();
        Bitmap box1 = new Bitmap(p);
        Bitmap box2 = new Bitmap(p);
        int rr, x, m, lev, wid;
        int[] lut = new int[256];
        int[,,] pic = new int[600, 600, 3];
        double dm;
        lev = 80;
        wid = 100;
        for (x = 0; x < 256; x += 1)
        {
            lut[x] = 255;
        }
        for (x = lev; x < (lev + wid); x++)
        {
            dm = ((double)(x - lev) / (double)wid) * 255f;
            lut[x] = (int)dm;
        }
        for (int i = 0; i < p.Width - 1; i++)
        {
            for (int j = 0; j < p.Height; j++)
            {
                c = box1.GetPixel(i, j);
                pic[i, j, 0] = c.R;
                pic[i, j, 1] = c.G;
                pic[i, j, 2] = c.B;
            }
        }
        for (int i = 0; i < p.Width - 1; i++)
        {
            for (int j = 0; j < p.Height; j++)
            {
                m = pic[i, j, 0];
                rr = lut[m];
                Color c1 = Color.FromArgb(rr, rr, rr);
                box2.SetPixel(i, j, c1);
            }

        }
       // box2.Save(Program.ocrChangeImagePath + "GrayBitmap2_" + Strings.filenameshijian() + ".png", System.Drawing.Imaging.ImageFormat.Png);
    }


    #endregion
}
